package cn.zxcoder.controller.login;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.zxcoder.Tools.ToolUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Api(tags = "图形验证码-api")
@RequestMapping("/api/img")
@RestController
public class CaptchaController {

    // 模拟缓存
    Jedis jedis = ToolUtil.jedis;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 给前端返回一个验证码图片
     *
     * @return
     */
    @ApiOperation("获取图形验证码")
    @GetMapping("/identifyImage")
    public void identifyImage(HttpServletResponse response,
                              HttpServletRequest request) throws IOException {

        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        // 验证码值
        String code = lineCaptcha.getCode();
        System.out.println("验证码值：" + code);

        //存入缓存的键
        String remoteAddr = request.getRemoteAddr();
        String key = "code:" + remoteAddr;
        System.out.println("存入jedis的值：   key:" + key);

        // 模拟把验证码的值存储到缓存(记得添加过期时间)

//        jedis.setex(key, 60, code);
        redisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);

        // 图形验证码对应的UUID,id和验证码一一对应，用于刷新、验证
        response.setHeader("codeId", key);
        // 输出到客户端
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            // 图形验证码写出，写出到流
            lineCaptcha.write(outputStream);
        } catch (Exception e) {
            System.out.println("图形验证码输出错误");
        }
    }
}
//    /**
//     * 给前端返回一个base64格式的图片，前端需要转换为图片
//     * @return
//     */
//    @ApiOperation("获取图形验证码base64")
//    @GetMapping("/identifyImageBase64")
//    public String identifyImageBase64() {
//        // 定义图形验证码的长和宽
//        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
//        // 验证码值
//        String code = lineCaptcha.getCode();
//        System.out.println("验证码值：" + code);
//        // 验证码以base64的格式返回到客户端
//        return lineCaptcha.getImageBase64Data();
//    }
//
//
//}